package com.os.ui;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import java.awt.*;

public class CustomTable extends JTable {

    public CustomTable(DefaultTableModel model) {
        setModel(model);
        setShowGrid(true);
        setIntercellSpacing(new Dimension(0, 0)); // 设置单元格间距为0
        setFillsViewportHeight(true);

        // 设置表头样式
        JTableHeader header = getTableHeader();
        header.setBackground(Color.DARK_GRAY);
        header.setForeground(Color.WHITE);
        header.setFont(new Font("宋体", Font.BOLD, 14));

        // 设置选中行的背景色
        setSelectionBackground(Color.CYAN);
    }

    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
        Component component = super.prepareRenderer(renderer, row, column);

        if (isRowSelected(row)) {
            component.setBackground(getSelectionBackground());
        } else {
            if (row % 2 == 0) {
                component.setBackground(Color.YELLOW); // 设置偶数行的背景色为黄色
            } else {
                component.setBackground(Color.WHITE); // 设置奇数行的背景色为白色
            }
        }

        return component;
    }

}
